<?php
namespace app\admin\controller;

use app\admin\validate\Shop;
use app\common\model\ApplyReg;
use app\common\model\Order;
use app\common\model\ShopsBanner;
use app\common\model\ShopsDepartment;
use app\common\model\ShopsManager;
use app\common\model\ShopsSeat;
use plug\SUtil;
use think\console\Input;
use think\Request;

class Shops extends Base
{
    public function __construct()
    {
        parent::__construct();
        $this->isLogin();
    }

    /**
     * @route('shopapply/applylist')
     * 申请注册商铺列表
     */
    public function applylist()
    {
//        // 获取搜索条件
        $get['shop_name'] = input('get.shop_name');
        $where = null;
        if($get['shop_name']){
            $where[] = ['al.shopname','like',"%".$get['shop_name']."%"];
        }
        $item = 'al.*,p.name as province,c.name as city,a.name as area';
        $model = new ApplyReg();
        $rs_data = $model
            ->alias('al')
            ->leftJoin([
                ['ddt_area p', 'al.province_code = p.id'],
                ['ddt_area c', 'al.city_code = c.id'],
                ['ddt_area a', 'al.area_code = a.id'],
            ])
            ->where($where)
            ->field($item)
            ->paginate($this->limit);
//        var_dump($rs_data->toArray());die;
        $tvar = array(
            "title" => "商铺注册申请列表",
            "time"  => time(),
            "data"  => $rs_data,
            "get"   => $get,
//            "isdisplay" => $isdisplay,
        );
        $page = $rs_data->render();
        $this->assign("data", $tvar);
        $this->assign('page', $page);
        return $this->fetch('shops/applylist');
    }


    /**
     * @route('shopapply/boxcheck')
     * 申请审核
     */
    public function BoxCheck()
    {
        $model = new ApplyReg();
        $get['applyreg_id'] = input('get.applyreg_id');
//        var_dump($get['applyreg_id']);die;
        if(request()->isAjax()){
            $param = request()->param();
            if(empty($param['applyreg_id']) || empty($param['status']) || empty($param['reasons'])){
                $this->error('必填项不能为空');
            }
            if(!empty($param['profit']) && $param['profit'] < 1){
                $this->error('分成比例不能小于1%');
            }
            $data = [
                'status' => $param['status'],
                'reasons' => $param['reasons'],
                'profit' => $param['profit'],
            ];
//            var_dump($param);die;
            $rs = $model->edit($data,$param['applyreg_id'],true);
            if($rs === false){
                $this->error($model->getError());
            }
            $this->success('操作成功','/shopapply/applylist');
        }
        $checkdetail = $model->where('applyreg_id','=',$get['applyreg_id'])->find();
//        var_dump($checkdetail);
        if(!$checkdetail){
            $this->error('不存在的审核','/shopapply/applylist');
        }
        $tvar = array(
            "title" => "添加账号",
            "time"  => time(),
            "applyreg_id" => $get['applyreg_id'],
        );
        $this->assign("data", $tvar);
        return $this->fetch('shops/boxcheck');
    }

    /**
     * @route('shops/shopslist')
     * 商铺管理列表
     */
    public function shopslist()
    {
//        // 获取搜索条件
        $get['shop_name'] = input('get.shop_name');
        $where = null;
        if($get['shop_name']){
            $where[] = ['shop_name','like',"%".$get['shop_name']."%"];
        }
//        var_dump(345);die;
        $model = new \app\common\model\Shops();
        $rs_data = $model->where($where)->paginate($this->limit);
        $tvar = array(
            "title" => "商铺管理列表",
            "time"  => time(),
            "data"  => $rs_data,
            "get"   => $get,
        );
//        var_dump(345);die;
        $page = $rs_data->render();
        $this->assign("data", $tvar);
        $this->assign('page', $page);
        return $this->fetch('shops/shopslist');
    }

    /**
     * @route('shops/shopinfo')
     * 商铺信息管理编辑
     */
    public function shopinfo()
    {
        if(input('handle') == "upload"){
            $res = \Upload::FileUpload('file','shopinfo',1024*1024*10,'jpg,png,jpeg,gif');
            if(!$res['data']){
                $this->result([],-1,$res['msg']);
            }
            $this->result($res['data']['file_path'],1);
        }
        $where = [
            'shop_id' => $this->_shopid,
        ];
        $model = new \app\common\model\Shops();
        $rs_data = $model->where($where)->find()->toArray();
        if(request()->isAjax()){
            $validate = new Shop();
            $param = input();
            $checkres = $validate->scene("EditInfo")->check($param);
            if (!$checkres) {
                $this->error($validate->getError());
            }
            $get = [
                'time_ranges' => $param['time_range'],
//                'persons' => $param['persons'],
//                'tips' => trim($param['tips'],' '),
//                'limit_number' => $param['limit_number'],
            ];
            $data = [
                "reserve_info" => json_encode($get,true),
                "is_business" => $param['state'],
                "shop_name" => $param['shopname'],
                "shop_phone" => $param['shopphone'],
                "address" => $param['address'],
                "ahead_days" => $param['ahead_days'],
                "mini_number" => $param['mini_number'],
                "notice_text" => $param['notice_text'],
                "shop_manager" => $param['shopmanager'],
                "imagesurl" => $param['imagesurl'],
                "kefu_image" => $param['kefu_image'],
                "remark" => $param['remark'],
            ];
            $rs = $model->where('shop_id','=',$this->_shopid)->data($data)->update();
            if($rs === false){
                $this->error($model->getError());
            }
            $this->success('操作成功');
        }
        if(in_array($rs_data['shop_type'],[2,3])){
            $is_display = true;
        } else {
            $is_display = false;
        }
        if(empty($rs_data['reserve_info'])){
            $rs_data['persons'] = NULL;
            $rs_data['limit_number'] = NULL;
            $rs_data['time_range'] = [];
            $rs_data['tips'] = '';
        } else {
            $reserve_info = json_decode($rs_data['reserve_info'],true);
            $rs_data['persons'] = NULL;
            $rs_data['time_range'] = $reserve_info['time_ranges'];
            $rs_data['tips'] = '';
            $rs_data['limit_number'] = NULL;
        }
        $tvar = array(
            "title" => "商铺信息管理",
            "time"  => time(),
            "info"  => $rs_data,
        );
        $this->assign("data", $tvar);
        $this->assign("is_display", $is_display);
        return $this->fetch('shops/shopinfo');
    }

    /**
     * @route('shops/updatestate')
     * 商铺状态修改
     */
    public function UpdateState()
    {
        $shopid = input('shopid');
        $model = new \app\common\model\Shops();
        $adminModel = new \app\common\model\Admin();
        $shop = $model->where('shop_id','=',$shopid)->find();
        if(empty($shop)){
            $this->error('不存在该商铺');
        }
        $data = $shop->toArray();
        if($data['state'] == 1){
            $param['state'] = 2;
        } else {
            $param['state'] = 1;
        }
        $admin = $adminModel->where('shop_id','=',$shopid)->find();
        if(empty($admin)){
            $this->error('不存在商铺对应管理员');
        }
        $admindata = $admin->toArray();
        if($admindata['status'] == 1){
            $adminparam['status'] = 2;
        } else {
            $adminparam['status'] = 1;
        }
        $model->startTrans();
        $rs = $model->edit($param,$data['shop_id']);
        if($rs === false){
            $model->rollback();
            $this->error("操作失败");
        }
        $rs2 = $adminModel->edit($adminparam,$admindata['user_id']);
        if($rs2 === false){
            $model->rollback();
            $this->error("操作失败");
        }
        $model->commit();
        $this->success('操作成功');
    }

    /**
     * @route('shops/reportlist')
     * 商铺报表
     */
    public function ReportList()
    {
        $orderModel = new Order();

        $get['shop_name'] = input('get.shop_name');
        $get['shop_type'] = input('get.shop_type');
        $get['shop_id'] = $this->_shopid;
        $get['time'] = input('get.time');

        $rs_data = $orderModel->ShopsReportFormList($get,$this->limit);
//        $rs_data = $orderModel->ShopsReportFormList($get,$this->limit)->toArray();
//        echo "<pre>";
//        var_dump($rs_data['data']);die;

        $tvar = array(
            "title" => "商铺报表",
            "time"  => time(),
            "data" => $rs_data,
            "get"  => $get,
        );
        $page = $rs_data->render();
        $this->assign("data", $tvar);
        $this->assign('page', $page);
        return $this->fetch('shops/reportlist');
    }


    /**
     * @route('shopbanner/shopbannerlist')
     * 店铺轮播图列表
     */
    public function shopbannerlist()
    {
        $limit = 10;
        $bannerModel = new ShopsBanner();
        $where = null;
        if($this->_shopid != 0){
            $where[] = ['shop_id','=',$this->_shopid];
        }
        $banners = $bannerModel->get_list($where,'sort','*',$limit);
        $page = $banners->render();

//        var_dump($banners);die;
        $tvar = array(
            "title" => "轮播图列表",
            "time"  => time(),
            "data"  => $banners,
            "type"  => $bannerModel::$paystatelist,
        );
        $this->assign("data", $tvar);
        $this->assign('page', $page);
        return $this->fetch('banner/shopbannerlist');
    }

    /**
     * @route('shopbanner/boxshopbanner')
     * 编辑添加轮播图
     */
    public function boxshopbanner(Request $request)
    {
        $bannerModel = new ShopsBanner();
        if(\request()->isAjax()){
            $param = $request->param();
            $data = [
                'title' => $param['title'],
                'pic_url' => $param['images'],
//                'to_url' => $param['tourl'],
                'sort' => $param['sort'],
                'shop_id' => $this->_shopid,
            ];
            if(!empty($param['original_images']) && $param['images'] != $param['original_images'] && file_exists($param['original_images'])){
                unlink($param['original_images']);
            }
//            var_dump($param);die;
            $rs = $bannerModel->edit($data,$param['s_b_id']);

            if($rs === false){
                $this->error($bannerModel->getError());
            }
            $this->success('操作成功','/shopbanner/shopbannerlist');
        }
        $id = input('get.s_b_id');
        $banner = null;
        if($id != 0){
            $where = [
                ['s_b_id','=',$id],
                ['shop_id','=',$this->_shopid],
            ];
            $banner = $bannerModel->getOne($where,'*');
        }
        $tvar = array(
            "title" => "添加轮播图",
            "time"  => time(),
            "data" => $banner,
            "s_b_id" => $id,
        );
//        var_dump($tvar);die;
        $this->assign("data", $tvar);
        return $this->fetch('banner/boxshopbanner');
    }

    /**
     * @route('shopbanner/delshopbanner')
     * 删除店铺轮播图
     */
    public function delshopbanner()
    {
        $id = $_GET['s_b_id'];
        $url = $_GET['image_url'];
        $bannerModel = new ShopsBanner();
//        var_dump($id);die;
        $shop_id = '';
        if($this->_shopid != 0){
            $shop_id = $this->_shopid;
        }
        if(file_exists($url)) {
            unlink($url);
        }
        $rs = $bannerModel->delshopbanner($id,$shop_id);
        if($rs === false){
            $this->error("删除失败");
        }
        $this->success('删除成功 ');
    }

	/**
	 * @route('shops/ShopSeatList')
	 * 商铺座位列表
	 */
	public function ShopSeatList(){
		$ShopsSeatModel = new ShopsSeat();
		$where = [
			'shop_id' => $this->_shopid
		];
		$list = $ShopsSeatModel->get_list_page($where);
		$page = $list->render();
		$tvar = array(
			"title" => "商铺座位列表",
			"list"  => $list,
		);
		$this->assign("data", $tvar);
		$this->assign('page', $page);
		return $this->fetch('shops/seat/shopseatlist');
	}

	/**
	 * @route('shops/editShopSeat')
	 * 添加、修改商铺座位
	 */
	public function editShopSeat(){
		$ShopsSeatModel = new ShopsSeat();
		$form = Input('post.form');
		if($form == 'submit'){
			$seat_id = Input('post.seat_id',0);
			$res = $ShopsSeatModel->edit([
				'shop_id' => $this->_shopid,
				'seat_num' => Input('post.seat_num',0),
			],$seat_id);
			if(!$res){
				$this->error("操作失败",'/Shops/ShopSeatList');
			}
			$this->success('操作成功','/Shops/ShopSeatList');
		}

		$seat_id = Input('get.seat_id',0);
		$info = $ShopsSeatModel->find($seat_id);
		$tvar = array(
			"title" => "商铺座位列表",
			'data' => $info,
			'seat_id' => $seat_id,
		);
		$this->assign("data", $tvar);
		return $this->fetch('shops/seat/boxshopseat');
	}

	/**
	 * @route('shops/delShopSeat')
	 * 删除商铺座位
	 */
	public function delShopSeat(){
		$ShopsSeatModel = new ShopsSeat();
		$seat_id = Input('post.seat_id',0);
		$res = $ShopsSeatModel->Del($seat_id);
		if(!$res){
			$this->error("操作失败",'/Shops/ShopSeatList');
		}
		$this->success('操作成功','/Shops/ShopSeatList');
	}

    /**
     * @route('shops/departmentlist')
     * 商铺线下部门列表
     */
    public function departmentlist(){
        $isdisplay = false;
        // 获取搜索条件
        //总部商铺ID为0，总部可以看到所有商品
        if($this->_shopid != 0){
            //商家身份只能看自己的
            $get['shop_id'] = $this->_shopid;
            //页面的搜索显示
            $isdisplay = true;
        }else{
            //总部的搜索功能
            $get['shop_id'] = input('get.shop_id');
        }
        $get['department_name'] = input('get.department_name');
        $get['is_del'] = 1;
        $field = 'd.*,s.shop_name';

        $Model = new ShopsDepartment();
        $data = $Model->get_list_page($field,$get,'',$this->limit);
//        var_dump($data);die;

        $tvar = array(
            "title" => "商铺线下部门列表",
            "time"  => time(),
            "data"  => $data,
            "get"   => $get,
            "isdisplay" => $isdisplay,
        );
//		print_r($tvar);die;
        $this->assign("data", $tvar);
        return $this->fetch('shops/department/departmentlist');
    }

    /**
     * @route('shops/boxedepartment')
     * 添加、修改商铺部门
     */
    public function boxedepartment(){
        $Model = new ShopsDepartment();
        $form = Input('post.');
        if(input('post.form') == 'submit'){
            $department_id = $form['department_id'];
            $data = [
                'department_name' => $form['department_name'],
                'printer_parameter' => $form['printer_parameter'],
                'is_print_all' => $form['is_print_all'],
                'admin_id' => $this->_userid,
            ];
            if($this->_shopid != 0){
                $data['shop_id'] = $this->_shopid;
            }
            $res = $Model->edit($data,$department_id);
            if(!$res){
                $this->error("操作失败");
            }
            $this->success('操作成功');
        }

        $department_id = Input('get.department_id',0);
        $info = $Model->getOne(['department_id' => $department_id]);
        $tvar = array(
            "title" => "编辑商铺部门",
            'data' => $info,
            'department_id' => $department_id,
        );
        $this->assign("data", $tvar);
        return $this->fetch('shops/department/boxedepartment');
    }

    /**
     * @route('shops/delShopDepartment')
     * 删除商铺部门
     */
    public function delShopDepartment(){
        $Model = new ShopsDepartment();
        $department_id = input('get.department_id',0);
        $res = $Model->Del($department_id);
        if(!$res){
            $this->error("操作失败");
        }
        $this->success('操作成功');
    }

    /**
     * @route('shops/managerlist')
     * 商铺线下管理员列表
     */
    public function managerlist(){
        $isdisplay = false;
        // 获取搜索条件
        //总部商铺ID为0，总部可以看到所有商品
        if($this->_shopid != 0){
            //商家身份只能看自己的
            $get['shop_id'] = $this->_shopid;
            //页面的搜索显示
            $isdisplay = true;
        }else{
            //总部的搜索功能
            $get['shop_id'] = input('get.shop_id');
        }
        $get['real_name'] = input('get.real_name');
        $get['is_del'] = 1;
        $field = 'm.*,s.shop_name';

        $Model = new ShopsManager();
        $data = $Model->get_list_page($field,$get,'',$this->limit);
//        var_dump($data);die;

        $tvar = array(
            "title" => "商铺线下管理员列表",
            "time"  => time(),
            "data"  => $data,
            "get"   => $get,
            "isdisplay" => $isdisplay,
        );
//		print_r($tvar);die;
        $this->assign("data", $tvar);
        return $this->fetch('shops/manager/managerlist');
    }

    /**
     * @route('shops/boxemanager')
     * 添加、修改商铺管理员
     */
    public function boxemanager(){
        $Model = new ShopsManager();
        $form = Input('post.');
        $manager_id = Input('manager_id',0);
        $info = $Model->getOne(['manager_id' => $manager_id]);
        if(input('post.form') == 'submit'){
            $manager_id = $form['manager_id'];
            $data = [
                'real_name' => $form['real_name'],
                'user_account' => $form['user_account'],
                'status' => $form['status'],
                'admin_id' => $this->_userid,
            ];
            $is_update_pass = false;
            if(empty($info) && empty($form['user_pass'])){
                $form['user_pass'] = 456789;
                $is_update_pass = true;
            }
            if(!empty($form['user_pass'])){
                $is_update_pass = true;
            }
            if($is_update_pass){
                // 密码随机验证码
                $data['pass_random'] = SUtil::random(6,0);
                // 生成密码
                $data['user_pass'] = SUtil::getHashBackend($form['user_pass'], $data['pass_random']);
            }
            if($this->_shopid != 0){
                $data['shop_id'] = $this->_shopid;
            }
            $res = $Model->edit($data,$manager_id);
            if(!$res){
                $this->error("操作失败");
            }
            $this->success('操作成功');
        }

        $tvar = array(
            "title" => "编辑商铺管理员",
            'data' => $info,
            'manager_id' => $manager_id,
        );
        $this->assign("data", $tvar);
        return $this->fetch('shops/manager/boxemanager');
    }

    /**
     * @route('shops/delShopManager')
     * 删除商铺管理员
     */
    public function delShopManager(){
        $Model = new ShopsManager();
        $manager_id = input('get.manager_id',0);
        $res = $Model->Del($manager_id);
        if(!$res){
            $this->error("操作失败");
        }
        $this->success('操作成功');
    }
}